from concurrent.futures import ThreadPoolExecutor
import socket

from net_cient import NetClient


def handle_client(client_sock, address):
    net_client = NetClient(client_sock, address)
    net_client.receive_request()


if __name__ == '__main__':
    try:
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server.bind(('127.0.0.1', 50001))
        server.listen(100)
        print("")
        print("Start server, listening port 50001.")
        
        with ThreadPoolExecutor(max_workers=20) as executor:
            while True:
                client_sock, address = server.accept()
                print(f"Client connect from {address}")
                # create a thread in thread pool
                executor.submit(handle_client, client_sock, address)
            # server.close()  # with 会自动关闭，但也可以显式调用
    except Exception as e:
        print(f"Error happens: {e}")
